package controllers

import (
	"auusoft/AuuWiki/Models"
	"crypto/md5"
	"encoding/hex"
	//"fmt"
	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

var (
	Ifadmin = "false"
)

func GetIfadmin() string {
	return Ifadmin
}

func (this *LoginController) Get() {
	this.Ctx.Request.ParseForm()
	todo := this.Ctx.Request.Form.Get("todo")
	if todo == "logout" {
		sess := this.StartSession()
		sess.Delete("username")
		sess.Delete("mylist")
	}

	this.TplNames = "login.html"
}

func (this *LoginController) Post() {
	this.Ctx.Request.ParseForm()
	username := this.Ctx.Request.Form.Get("username")
	password := this.Ctx.Request.Form.Get("password")
	//remember := this.Ctx.Request.Form.Get("remember")
	//fmt.Println("start")
	userInfos, errorstr := models.GetUserInfoByUsername(username, 0, -1)
	//fmt.Println("end")

	if errorstr != "" {
		this.Data["errormsg"] = "Access Database Error"
		this.TplNames = "login.html"
		return
	}

	count := len(userInfos)

	if count <= 0 {
		this.Data["errormsg"] = "Cannot Found User Error"
		this.TplNames = "login.html"
		return
	}

	userInfo := userInfos[0]
	h := md5.New()
	h.Write([]byte(password))

	password = hex.EncodeToString(h.Sum(nil)) // 输出加密结果
	//fmt.Println("%s\n", password)

	if username == userInfo.UserName && password == userInfo.Password {
		Ifadmin = userInfo.Ifadmin
		sess := this.StartSession()
		sess.Set("username", username)
		sess.Set("mylist", []string{"一切从这里开始"})

		this.Ctx.Redirect(302, "/")
	} else {
		this.Data["errormsg"] = "Login Error" // + userInfo.UserName + "," + userInfo.Password
		this.TplNames = "login.html"
	}

}
